package g3pd.gradep.virdgm;

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class VirdMemLoader {
    String inputFile;
    String typeAttr;
    int dimensionsAttr;
    int sizeAttr;
    int [] dateAttr;
    
    VirdMemLoader(String inputFile) {
        this.inputFile = inputFile;
        
        try {
            OpenFile();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public void OpenFile() throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(inputFile);
        Element elem = doc.getDocumentElement();
        NodeList nodelist = elem.getChildNodes();
        parseFile(nodelist);
    }
    
    public int getDimensionsAttr() {
        return dimensionsAttr;
    }
    
    public void setDimensionsAttr(int dimensionsAttr) {
        this.dimensionsAttr = dimensionsAttr;
    }
    
    public int getSizeAttr() {
        return sizeAttr;
    }
    
    public void setSizeAttr(int sizeAttr) {
        this.sizeAttr = sizeAttr;
    }
    
    public String getTypeAttr() {
        return typeAttr;
    }
    
    public void setTypeAttr(String typeAttr) {
        this.typeAttr = typeAttr;
    }
    
    public int [] getDateAttr() {
        return dateAttr;
    }
    
    public void setDateAttr(int [] dateAttr) {
        this.dateAttr = dateAttr;
    }
    
    private int [] parseDateAttr(String dateAttr) throws Exception {
        String [] dateList = dateAttr.split(", ");
        int [] dateValues = new int[dateList.length - 1];
        for(int i = 0; i < dateList.length - 1; i++) {
            String val = dateList[i];
            dateValues[i] = Integer.parseInt(val);
        }
        return dateValues;
    }
    
    private void parseFile(NodeList nl) throws Exception {
        for(int i = 0; i < nl.getLength(); i++) {
            Node nodes = nl.item(i);
            if(nodes.getNodeType() == Node.ELEMENT_NODE) {
                if(nodes.getNodeName().equals("posicao")) {
                    String pos1 = ((Element)nodes).getAttribute("dimensao");
                    String pos2 = ((Element)nodes).getAttribute("tamanho");
                    
                    setDimensionsAttr(Integer.parseInt(pos1));
                    setSizeAttr(Integer.parseInt(pos2));
                }
                
                if(nodes.getNodeName().equals("valores")) {
                    NodeList nodo = nodes.getChildNodes();
                    String val = nodo.item(0).getNodeValue();
                    
                    setTypeAttr(val);
                }
                
                if(nodes.getNodeName().equals("dados")) {
                    Node nodo = nodes.getChildNodes().item(0);
                    String vals = nodo.getNodeValue();
                    
                    setDateAttr(parseDateAttr(vals));
                }
            }
        }
    }
}
